
from . import admin_blue
from flask import render_template,g,request,jsonify,current_app,session,redirect
from info.utils.commons import login_required
from info.utils.response_code import RET
from info.models import User
import time
from datetime import datetime,timedelta

@admin_blue.route('/index')
@login_required
def index():
    user=g.user
    return render_template('admin/index.html',user=user.to_dict())



@admin_blue.route('/login',methods=['GET','POST'])
def admin_login():
    if request.method=='GET':
        return render_template('admin/login.html')
    username=request.form.get('username')
    password=request.form.get('password')
    if not all([username,password]):
        return render_template('admin/login.html',errmsg='参数缺失')
    try:
        user=User.query.filter(username==User.mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html',errmsg='查询数据库失败')
    if not user:
        return render_template('admin/login.html',errmsg='没有管理员数据')
    if not user.check_password(password):
        return render_template('admin/login.html', errmsg='管理员密码不正确')
    if not user.is_admin:
        return render_template('admin/login.html', errmsg='不是管理员')
    session['user_id']=user.id
    session['nick_name']=user.nick_name
    session['mobile']=user.mobile
    session['is_admin']=True
    return redirect('/admin/index')


# 用户统计
@admin_blue.route('/user_count')
def user_count():
    total_count=0
    try:
        total_count=User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库总人数失败')
    mon_count=0
    try:
        now=time.localtime()
        # 拼接一个日期格式的字符串
        mon_begin='%d-%02d-01'%(now.tm_year,now.tm_mon)
        mon_begin_data=datetime.strptime(mon_begin,'%Y-%m-%d')
        mon_count=User.query.filter(User.is_admin==False,User.create_time>mon_begin_data).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库月增加总人数失败')
    day_count=0
    try:
        day_begin='%d-%02d-%02d'%(now.tm_year,now.tm_mon,now.tm_mday)
        day_begin_data=datetime.strptime(day_begin,'%Y-%m-%d')
        day_count=User.query.filter(User.is_admin==False,User.create_time>day_begin_data).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库日增加总人数失败')
    # 统计用户活跃度
    active_count=[]
    active_time=[]
    now_str = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
    now_data = datetime.strptime(now_str, '%Y-%m-%d')
    for d in range(30):
        begin_date = now_data - timedelta(days=d)
        end_date = now_data - timedelta(days=(d - 1))

        try:
            count=User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<end_date).count()
        except  Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='查询活跃人数失败')
        # 日期对象没法添加到列表里，所以先把它转成字符串
        begin_str=datetime.strftime(begin_date,'%Y-%m-%d')
        active_count.append(count)
        active_time.append(begin_str)
    # 倒叙是为了日期近的在前边
    active_count.reverse()
    active_time.reverse()

    data={
        'total_count':total_count,
        'mon_count':mon_count,
        'day_count':day_count,
        'active_count':active_count,
        'active_time':active_time
    }

    return render_template('admin/user_count.html',data=data)

    pass





